<template>
  <el-card shadow="navar">
    <el-row :gutter="15">
      <el-col :span="8">
        <MmvGatherComponent :seckilData="formData"></MmvGatherComponent>
      </el-col>
      <el-col :span="16">
        <el-row :gutter="15">
          <el-form
            ref="elForm"
            :model="formData"
            :rules="rules"
            size="medium"
            label-width="140px"
          >
            <el-col :span="24">
              <el-form-item label="活动名称" prop="collectName">
                <el-input
                  v-model.trim="formData.collectName"
                  placeholder="请输入活动名称"
                  :maxlength="50"
                  show-word-limit
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动开始时间" prop="timeStart">
                <el-date-picker
                  v-model.trim="formData.timeStart"
                  type="datetime"
                  placeholder="请选择开始时间"
                  :style="{ width: '100%' }"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptionsStart"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动结束时间" prop="timeEnd">
                <el-date-picker
                  v-model.trim="formData.timeEnd"
                  type="datetime"
                  placeholder="请选择结束时间"
                  :style="{ width: '100%' }"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptionsEnd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="虚拟报名人数量" prop="inventedEnrollNumber">
                <el-input
                  v-model.trim="formData.inventedEnrollNumber"
                  placeholder="请输入报名人数"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动门店/部门" prop="applicableUnitNo">
                <el-select
                  v-model="formData.applicableUnitNo"
                  @change="applicableUnitNoChange"
                  multiple
                  placeholder="请选择活动门店/部门"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="item in applicableUnitOptions"
                    :key="item.applicableUnitNo"
                    :label="item.applicableUnit"
                    :value="item.applicableUnitNo"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动封面" prop="coverImage" required>
                <MmvUploadImage @upImg="upcoverImage" size="2" ref="coverImage">
                  <el-button size="small" type="primary" icon="el-icon-upload"
                    >添加图片</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持JPG/JPEG/PNG，尺寸375px*256px，不超过2M，仅限1张图片
                  </div>
                </MmvUploadImage>
              </el-form-item>
              <el-form-item label="详情封面" prop="detailImage" required>
                <MmvUploadImage
                  @upImg="updetailImage"
                  :more="true"
                  size="2"
                  ref="detailImage"
                >
                  <el-button size="small" type="primary" icon="el-icon-upload"
                    >添加图片</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持JPG/JPEG/PNG，尺寸375px*256px，不超过2M，可选多张图片
                  </div>
                </MmvUploadImage>
              </el-form-item>
              <el-form-item label="分享封面" prop="shareImage" required>
                <MmvUploadImage @upImg="upshareImage" size="2" ref="shareImage">
                  <el-button size="small" type="primary" icon="el-icon-upload"
                    >添加图片</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持JPG/JPEG/PNG，尺寸375px*256px，不超过2M，仅限1张图片
                  </div>
                </MmvUploadImage>
              </el-form-item>
              <el-form-item label="活动描述" prop="collectContent">
                <editor v-model="formData.collectContent" :min-height="192" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item size="large">
                <el-button @click="goBack">取消</el-button>
                <el-button type="primary" @click="submitForm" v-onceClick
                  >提交</el-button
                >
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import { applicableUnitList } from '@/api/coupon/manage.js'
import { collect, getGatherById } from '@/api/activity/gather'

import MmvUploadImage from '../../components/mmv-upload-image.vue'
import MmvAddGoods from '../../components/mmv-add-seckill.vue'
import MmvGatherComponent from '../../components/activity-mobile/mmv-gather-component.vue'
export default {
  dicts: ['activity_delFlag'],
  components: {
    MmvUploadImage,
    MmvAddGoods,
    MmvGatherComponent,
  },
  props: [],
  data() {
    // 验证开始时间的规则
    var checkTimeStart = (rule, value, callback) => {
      if (this.formData.timeEnd != '' && value > this.formData.timeEnd) {
        callback(new Error('活动开始时间需小于活动结束时间'))
      }
      if (
        this.formData.timeStart &&
        this.formData.timeEnd &&
        this.formData.timeStart != '' &&
        this.formData.timeEnd != ''
      ) {
        this.$refs['elForm'].clearValidate('timeEnd')
      }
      return callback()
    }
    // 验证结束时间的规则
    var checkTimeEnd = (rule, value, callback) => {
      if (
        this.formData.timeEnd != '' &&
        this.formData.timeStart != '' &&
        value < this.formData.timeStart
      ) {
        callback(new Error('活动结束时间需大于活动开始时间'))
      }
      if (
        this.formData.timeStart &&
        this.formData.timeEnd &&
        this.formData.timeStart != '' &&
        this.formData.timeEnd != ''
      ) {
        this.$refs['elForm'].clearValidate('timeStart')
      }
      return callback()
    }
    return {
      // 开始结束日期限制
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.formData.timeEnd) {
            return time.getTime() >= new Date(this.formData.timeEnd).getTime()
          }
        },
      },
      // 结束日期限制
      pickerOptionsEnd: {
        disabledDate: (time) => {
          if (this.formData.timeStart) {
            return time.getTime() <= new Date(this.formData.timeStart).getTime()
          }
        },
      },
      //门店数据
      applicableUnitOptions: [],
      //表单数据
      formData: {
        collectName: '',
        timeStart: '',
        timeEnd: '',
        inventedEnrollNumber: null,
        applicableUnitNo: [],
        coverImage: '',
        detailImage: '',
        shareImage: '',
        activityUnit: [],
      },
      // 表单验证
      rules: {
        collectName: [
          {
            required: true,
            message: '请输入活动标题',
            trigger: 'blur',
          },
        ],
        status: [
          {
            required: true,
            message: '请输入活动状态',
            trigger: 'change',
          },
        ],
        timeStart: [
          {
            required: true,
            message: '请输入活动开始时间',
            trigger: 'change',
          },
          { validator: checkTimeStart, trigger: 'change' },
        ],
        timeEnd: [
          {
            required: false,
            message: '请输入活动结束时间',
            trigger: 'change',
          },
          { validator: checkTimeEnd, trigger: 'change' },
        ],
        inventedEnrollNumber: [
          {
            required: true,
            message: '请输入虚拟报名人数量',
            trigger: 'blur',
          },
          {
            pattern: /^([1-9]\d*)$/,
            message: '只能输入正整数',
            trigger: 'blur',
          },
        ],
        applicableUnitNo: [
          {
            required: true,
            message: '请选择活动地点',
            trigger: 'change',
          },
        ],
        coverImage: [
          {
            required: true,
            message: '请选择活动封面',
            trigger: 'blur',
          },
        ],
        detailImage: [
          {
            required: true,
            message: '请选择详情封面',
            trigger: 'blur',
          },
        ],
        shareImage: [
          {
            required: true,
            message: '请选择分享封面',
            trigger: 'blur',
          },
        ],
        collectContent: [
          {
            required: true,
            message: '请输入活动描述',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  mounted() {
    Promise.all([this.getApplicableUnitList()]).then(([res]) => {
      if (this.$route.params.id) {
        this.$nextTick(() => {
          this.getGatherDetail()
        })
      }
    })
  },
  methods: {
    // 获取活动门店
    getApplicableUnitList() {
      applicableUnitList().then((res) => {
        this.applicableUnitOptions = res.data
      })
    },
    applicableUnitNoChange(val) {
      this.formData.activityUnit = val.map((item) => {
        return this.applicableUnitOptions.filter((e) => {
          return e.applicableUnitNo === item
        })[0]
      })
      this.$forceUpdate()
    },
    // 获取集客活动详情
    getGatherDetail() {
      getGatherById({ id: this.$route.params.id }).then((res) => {
        this.formData = res.data
        this.$nextTick(() => {
          this.$refs.coverImage.previewToUrl(res.data.coverImage)
          this.$refs.detailImage.previewToUrl(res.data.detailImage)
          this.$refs.shareImage.previewToUrl(res.data.shareImage)
        })
        this.formData.applicableUnitNo = res.data.activityUnit.map((item) => {
          return item.applicableUnitNo
        })
      })
    },
    upcoverImage(url) {
      // 活动封面上传成功地址
      this.formData.coverImage = url[0]
      this.$refs['elForm'].validateField('coverImage')
    },
    updetailImage(url) {
      // 详情封面上传成功地址
      this.formData.detailImage = url.join(',')
      this.$refs['elForm'].validateField('detailImage')
    },
    upshareImage(url) {
      // 分享封面上传成功地址
      this.formData.shareImage = url[0]
      this.$refs['elForm'].validateField('shareImage')
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) {
          this.$message.error('验证不通过，请检查输入')
          return
        } else {
          if (
            this.$route.params.type === 'copy' ||
            this.$route.params.type === 'add'
          ) {
            delete this.formData.id
          }
          collect(this.formData).then((res) => {
            this.$message.success(res.msg)
            this.goBack()
          })
        }
      })
    },
    goBack() {
      this.$router.go(-1) // 返回
      //关闭子页面
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex(
          (item) => item.path === this.$route.path
        ),
        1
      )
      this.$router.push(
        this.$store.state.tagsView.visitedViews[
          this.$store.state.tagsView.visitedViews.length - 1
        ].path
      )
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
  },
}
</script>
<style scoped>
.img {
  height: 300px;
  border: 1px solid #ccc;
  display: block;
  border-radius: 5px;
  margin-bottom: 15px;
}
</style>
